package com.example.controller;

import com.example.pojo.vo.PhotoUserID;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@Slf4j
@RestController
@RequestMapping("/faceSearch")
public class FaceSearchController {

    public static final String API_KEY = "rhhCttgVdhBAByGyaEpkzK3G";
    public static final String SECRET_KEY = "MazQE6UhXk0Wg8xiHPwMD4SP6M6JWo2e";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    @PostMapping("/search")
    public Result searchFace(@org.springframework.web.bind.annotation.RequestBody PhotoUserID photoUserID)  throws IOException, JSONException {


        //System.out.println(photoUserID);
        String photoData=photoUserID.getPhotoData();
        Integer userId = photoUserID.getUserId();

        //System.out.println(userId);
        MediaType mediaType = MediaType.parse("application/json");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\bd.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        //photoData=photoData.substring(10,photoData.length()-2);
        //System.out.println(photoData);
        RequestBody body = RequestBody.create(mediaType, String.format("{\"group_id_list\":\"111\",\"image\":\"%s\",\"image_type\":\"BASE64\"}", photoData));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        //System.out.println(response.body().string());

        System.out.println("krg");
        System.out.println(userId);


        String jsonResponse = response.body().string();
        System.out.println(jsonResponse);
        JSONObject jsonObject = new JSONObject(jsonResponse);

        // 检查"result"键是否存在并且是一个JSONObject
        if (jsonObject.has("result") && !jsonObject.isNull("result") && jsonObject.get("result") instanceof JSONObject) {

            JSONObject result = jsonObject.getJSONObject("result");

            if (result.has("user_list") && !result.isNull("user_list")) {
                JSONArray userList = result.getJSONArray("user_list");
                for (int i = 0; i < userList.length(); i++) {
                    JSONObject user = userList.getJSONObject(i);
                    Integer userIdFromFaceKu = Integer.valueOf(user.getString("user_id"));

                    double score = user.getDouble("score");
                    System.out.println("user_id: " + userIdFromFaceKu);
                    System.out.println("score: " + score);
                    System.out.println(userIdFromFaceKu.equals(userId));
                    System.out.println(score>80.0);
                    if(userIdFromFaceKu.equals(userId)&&score>80.0){
                        return Result.success(1);
                    }else{
                        return Result.error("非本人");
                    }
                }
            }else{
                System.out.println("jgrg");
            }
        } else {
            // 处理"result"键不存在或者不是JSONObject的情况
            System.out.println("Error: 'result' key is missing or not a JSONObject.");
        }
        return Result.error("人脸库中无此人脸");
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}